$(document).ready(function () {


    layui.use(function () {

        var layer = layui.layer;

        // 表格
        form = layui.form;
        form.on('select(status)', function (data) {//监听状态
            $('div[lay-filter="search"]').click();
        });
        form.on('select(type)', function (data) {//监听周期
            $('div[lay-filter="search"]').click();
        });
        form.on('submit(search)', function (data) {//监听查询提交
            params = data.field;
            params.pageSize = 10;
            queryTable();
            return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
        });


        form.on('submit(edit)', function (data) {//监听新增修改提交

            var selectArr = xmSel.getValue();
            var persons = selectArr.map(item => item.id)



            let msgType = "";
            if (curId) {
                msgType = "编辑"
                data.field.id = curId
            } else {
                msgType = "新增"
            }

            var time = data.field.time.split(' - ')
            data.field.beginTime = time[0]
            data.field.endTime = time[1]

            data.field.projects = [
                {
                    "projectId": data.field.projectId,
                    "trainNum": data.field.trainNum
                }
            ]
            data.field.persons = persons;

            new AjaxChain()
                .setUrl('/train/plan/save')
                .setMethod('post')
                .setData(JSON.stringify(data.field))
                .then(data => {
                    layer.close(drawer);
                    layer.msg(msgType + '成功', { icon: 1, time: 2000 });
                    queryTable()
                })
                .catch(err => {
                    console.error('请求异常:', err);
                })
                .send();


            return false;
        });

        initSubMenu();
        queryTable();


        new ST().trainProject().then(data => { trainProject = data })

    });
})
var params = {};//查询条件参数
var form, unit;
var drawer;//抽屉实例
var curId = null;//当前选中物资ID
var trainProject = ''

//查询物资类型列表
queryTable = () => {
    let toolWidth = window.innerWidth / 1920 * 240
    layui.use('table', function () {
        var table = layui.table;

        //展示已知数据
        table.render({
            elem: '#table'
            , text: {
                none: '暂无数据'
            }
            , method: 'get'
            , url: ajaxPrefix() + "/train/plan/list"
            , headers: {
                SessionId: JSON.parse(localStorage.getItem('sessionId'))
            }
            , where: params
            , parseData: function (res) { //res 即为原始返回的数据
                return {
                    "code": res.status == 200 ? 0 : 1, //解析接口状态
                    "msg": res.message, //解析提示文本
                    "count": res.result.total, //解析数据长度
                    "data": res.result.data //解析数据列表
                };
            }
            , request: {
                pageName: 'pageNum' //页码的参数名称，默认：page
                ,
                limitName: 'pageSize' //每页数据量的参数名，默认：limit
            }
            , cols: [[ //标题栏
                { field: 'name', title: '计划名称', align: "center" }
                , { field: 'typeDesc', title: '周期类型', align: "center" }
                , { field: 'beginTime', title: '开始时间', align: "center" }
                , { field: 'endTime', title: '结束时间', align: "center" }
                , {
                    title: '状态', align: "center",
                    templet: '#ID-table-templet-switch'
                }
                , {
                    flex: 'right',
                    title: '操作',
                    align: 'center',
                    width: toolWidth,
                    templet: function (d) {
                        let res = JSON.stringify(d);
                        return `<div class="table-tool">
                                <div onclick='tableHandle(1,${res})' class="table-edit layui-btn">
                                  <img src="../static/img/edit.png">编辑
                                </div>
                                <div onclick='tableHandle(2,${res})' class="table-del layui-btn">
                                  <img src="../static/img/del.png">删除
                                </div>
                              </div>`;
                    },
                },
            ]]
            , height: 'full'
            // ,skin: 'line' //表格风格
            , even: true
            , page: { //支持传入 laypage 组件的所有参数（某些参数除外，如：jump/elem） - 详见文档
                layout: ['count', 'prev', 'page', 'next', 'skip'] //自定义分页布局
                //,curr: 5 //设定初始在第 5 页
                , groups: 3 //只显示 1 个连续页码
                , first: false //不显示首页
                , last: false //不显示尾页

            }
            , done: function (res, curr, count) {

                $('.layui-table-cell').height($('.contain-table-list').height() / 20);
            },

        });

        layui.form.on('switch(templet-status)', function (obj) {

            var id = this.value;

            var name = this.name;
            new AjaxChain()
                .setUrl('/train/plan/'+ (obj.elem.checked ? 'start' : 'stop'))
                .setData({
                    id: id,
                })
                .then(data => {
                    layer.msg('操作成功', { icon: 1, time: 1500 });
                })
                .catch(err => {
                    console.error('请求异常:', err);
                })
                .send();


        });

    });
}


// 列表功能按钮操作
tableHandle = (type, res) => {
    switch (type) {
        case 1://编辑
            curId = res.id
            openDrawer(2, res)
            break;
        case 2://删除

            layer.confirm('确定删除该记录吗？', { icon: 3 }, function () {

                new AjaxChain()
                    .setUrl('/train/plan/delete')
                    .setData({ id: res.id })
                    .then(data => {
                        layer.msg('删除成功', { icon: 1, time: 1500 });
                        queryTable();
                    })
                    .catch(err => {
                        console.error('请求异常:', err);
                    })
                    .send();
            });
            break;

        case 3://新增 
            curId = null;
            openDrawer(1)
            break;


        default:
            break;
    }
}



openDrawer = (type, res) => {
    drawer = layer.open({
        title: '1',
        type: 1,
        offset: '4%',
        area: ['80%', '100%'],
        shade: 0.4,
        shadeClose: false,
        id: 'edit-offset',
        success: function (layero, index, that) {

            layui.laydate.render({
                elem: '#laydate-time',
                range: true,
            });

            if (res) {
                res.time = res.beginTime.split(' ')[0] + ' - ' + res.endTime.split(' ')[0]

                queryNodes(res.id)

                new AjaxChain()
                    .setUrl('/train/plan/project/list')
                    .setData({ id: res.id })
                    .then(data => {
                        if (data.length > 0) {

                            res.projectId = data[0].projectId
                            res.trainNum = data[0].trainNum
                            form.val('editForm', res);

                        }

                    })
                    .catch(err => {
                        console.error('请求异常:', err);
                    })
                    .send();


            } else {
                queryNodes()
                form.render(null, 'editForm');
            }

        },
        content: `<form class="layui-form layui-form-pane" id="add-form"  lay-filter="editForm"  action="">
                    <div class="form-item" style="height: 0.56rem;display: flex;justify-content: space-between;">
                        <div class="form-item layui-col-md4">
                            <label class="layui-form-label">计划名称</label>
                            <div class="layui-input-block">
                                <input type="text" name="name" lay-affix="clear" placeholder="请输入" lay-verify="required"
                                    class="layui-input">
                            </div>
                        </div>
                        <div class="form-item">
                            <label class="layui-form-label">计划周期</label>
                            <div class="layui-input-block">
                                <input type="text" name="time" id="laydate-time" lay-affix="clear" placeholder="请选择"
                                    class="layui-input">
                            </div>
                        </div>
                        <div class="form-item  layui-col-md4">
                            <label class="layui-form-label">周期类型</label>
                            <div class="layui-input-block">
                                <select name="type" lay-filter="" lay-verify="required">
                                    <option value="">请选择</option>
                                    <option value="1">每天</option>
                                    <option value="2">每周</option>
                                    <option value="3">每月</option>
                                </select>
                            </div>
                        </div>
                    </div>
                    <div class="form-item">
                        <label class="layui-form-label">参与人员</label>
                        <div class="layui-input-block">
                            <div id="persons" class="xm-select-demo"></div>
                        </div>
                    </div>
                    <div class="form-item" style="margin:4.5rem 0.2rem 0;">
                        <label class="layui-form-label">训练项目</label>
                        <div class="layui-input-block">
                            <select name="projectId" lay-filter="" lay-search="{fuzzy: true}">
                                ${trainProject}
                            </select>
                        </div>
                    </div>
                    <div class="form-item  layui-col-md4">
                        <label class="layui-form-label">训练次数</label>
                        <div class="layui-input-block">
                            <input type="text" name="trainNum" lay-affix="number" min=1 placeholder="请输入" lay-verify="required"
                                class="layui-input">
                        </div>
                    </div>
                    <div class="form-item pane-tool" style="height: 0.56rem;margin-top: 0.3rem;" >
                        <button class="layui-btn" lay-submit lay-filter="edit">保存</button>
                    </div>
                </form>`
    });

}


var xmSel = null
queryNodes = (planId) => {

    new AjaxChain()
        .setUrl('/person/list/all')
        .then(data => {

            xmSel = xmSelect.render({
                el: '#persons',
                template({ item, sels, name, value }) {
                    return `<img title="查看" src="/images/${item.photoPath}"
                             style="width: 0.4rem;height: 0.4rem;margin-right: 0.1rem;">`+ name + '<span style="position: absolute; right: 10px; color: #8799a3">' + item.id + '</span>'
                },
                searchTips: '输入姓名查询',
                filterable: true,
                toolbar: {
                    show: true,
                },
                prop: {
                    value: 'id',
                },
                model: {
                    type: 'relative',
                },
                data: data
            })


            if (planId) {
                new AjaxChain()
                    .setUrl('/train/plan/person/list?id=' + planId)
                    .then(data => {
                        var d = data.map(item => item.personId);
                        xmSel.setValue(d)

                    })
                    .send();
            }

        })
        .send();
}